var app = {
    format:function(str){
        return str > 9 ? str + "" : "0" + str;
    },
    init:function(){
        this.isAdmin = false;
        this.getCurrentUser();
        var that;
        $.fn.serializeObject = function() {  
            var o = {};  
            var a = this.serializeArray();  
            $.each(a, function() {  
                if (o[this.name]) {  
                    if (!o[this.name].push) {  
                        o[this.name] = [ o[this.name] ];  
                    }  
                    o[this.name].push(this.value || '');  
                } else {  
                    o[this.name] = this.value || '';  
                }  
            });  
            return o;  
        }  
        this.param = {
            startDate:"2018-01-01",
            endDate:"2018-11-31",
            stationName: "",
            pageSize:10,
            pageNo:1
        }
        this.bindEvent();
        var now = new Date();
        var initDate = now.getFullYear() + "-01-01" + " - " + now.getFullYear() + "-" + this.format(now.getMonth()+1) + "-" + this.format(now.getDate());
        layui.use('laydate', function(){
            var laydate = layui.laydate;
            //执行一个laydate实例
            laydate.render({
                elem: '#date', //指定元素,
                range: true,
                min:"100-1-1",
                format: "yyyy-MM-dd",
                value:initDate
            });
        });
    },
    bindEvent:function(){
        var that = this;
        $(document).on("click",".search",function(e){
            that.param.stationName = $(".station-name").val();
            that.param.startDate = $("#date").val().split(" - ")[0];
            that.param.endDate = $("#date").val().split(" - ")[1];
            that.getRecordList(that.param);
            e.preventDefault();
            e.stopPropagation();
        });
        $(document).on("click",".export",function(e){
            layer.confirm('您会导出' + that.total  +'条记录，需要等待较长时间，是否确定导出？', {
                btn: ['确定','取消'] //按钮
              }, function(){
                that.exportExcel();
              }, function(){
                
              });
            e.preventDefault();
            e.stopPropagation();
        })
        $(document).on("click",".add",function(e){
            that.layerIndex = layer.open({
                type: 1,
                title: "新增台站记录",
                closeBtn: 1,
                shadeClose:false,
                content: template("recordTpl",{}),
                btn: ['确定', '取消'],
                area: ['500px', '440px']
                ,yes: function(index, layero){
                  //按钮【按钮一】的回调
                  if(that.verify()){
                    that.add();
                  }
                }
                ,btn2: function(index, layero){
                  //按钮【按钮二】的回调
                  //return false 开启该代码可禁止点击该按钮关闭
                },
                success:function(){
                    layui.use('laydate', function(){
                        var laydate = layui.laydate;
                        //执行一个laydate实例
                        laydate.render({
                            elem: '#tdate', //指定元素,
                            min:"100-1-1",
                            format: "yyyy-MM-dd"
                        });
                    });
                }
            });
        });
    },
    exportExcel:function(){
        var that = this;
        that.loading = layer.load(0, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
        var param = {
            stationName: $(".station-name").val(),
            startDate: $("#date").val().split(" - ")[0],
            endDate: $("#date").val().split(" - ")[1],
            type: $('input[name=type]:checked').val(),
        };
        $.ajax({
            url:'/api/v1/meteorology/station/exportTemp',
            type:'post',
            data:param,
            success:function(res){
                layer.close(that.loading);
                if(res.errcode == "0000"){
                    layer.msg("导出成功",{icon: 1});
                    window.open(res.data.exportPath); 
                }else{
                    layer.msg(res.errmsg,{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    verify:function(){
        return true;
    },
    add:function(){
        var that = this;
        var param = $("#recordForm").serializeObject();
        var type = $('input[name=type]:checked').val();
        var url = type === 1 ? '/api/v1/meteorology/station/save735' : '/api/v1/meteorology/station/saveday';
        $.ajax({
            url: url,
            type:'post',
            data:JSON.stringify({tempday:param}),
            contentType:"application/json",
            success:function(res){
                if(res.errcode == "0000"){
                    layer.msg("新增成功！",{icon: 1});
                    that.getRecordList(that.param);
                    layer.close(that.layerIndex);
                }else{
                    layer.msg(res.errmsg,{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    getCurrentUser:function(){
        var that = this;
        common.getCurrentUser().then(function(res){
            that.getRecordList(that.param);
            that.isAdmin = !!res.data.isAdmin;
            if(res.data.isAdmin){
                $(".add-zone").addClass("show");
            }
        })
    },
    renderTable:function(data){
        var that = this;
        layui.use('table', function(){
            var table = layui.table;
            var cols = [[ //表头
                {field: 'station', title: '台站编号', sort: false}
                ,{field: 'stationname', title: '台站名称', }
                ,{field: 'averageTemperature', title: '平均气温', sort: false}
                ,{field: 'max', title: '最高气温'} 
                ,{field: 'min', title: '最低气温'}
                ,{field: 'rain', title: '降水量', sort: false}
                ,{field: 'tdate', title: '记录日期'}
                ]];
            if(that.isAdmin){
                cols[0].push({title: '操作',toolbar: '#barDemo'});
            }
            table.render({
                elem: '#demo'
                //,url: '/demo/table/user/' //数据接口
                ,data: data.entities ? data.entities : []
                ,limit:data.pageSize
                ,cellMinWidth:100
                ,text: {
                    none: '暂无相关数据' //默认：无数据
                }
                ,cols: cols
                ,page: false
                ,loading: true
            });  
            //监听工具条
            table.on('tool(test)', function(obj){
                var data = obj.data;
                if(obj.event === 'del'){
                    layer.confirm('确定删除该记录吗？', function(index){
                    //obj.del();
                    that.delete(data);
                    layer.close(index);
                    });
                } else if(obj.event === 'edit'){
                    data.fromEdit = 1;
                    that.layerIndex = layer.open({
                        type: 1,
                        title: "编辑台站记录",
                        closeBtn: 1,
                        shadeClose:false,
                        content: template("recordTpl",data),
                        btn: ['确定', '取消'],
                        area: ['500px', '440px']
                        ,yes: function(index, layero){
                          //按钮【按钮一】的回调
                          if(that.verify()){
                            that.edit(data);
                          }
                        }
                        ,btn2: function(index, layero){
                          //按钮【按钮二】的回调
                          //return false 开启该代码可禁止点击该按钮关闭
                        },
                        success:function(){
                            layui.use('laydate', function(){
                                var laydate = layui.laydate;
                                //执行一个laydate实例
                                laydate.render({
                                    elem: '#tdate', //指定元素,
                                    min:"100-1-1",
                                    format: "yyyy-MM-dd"
                                });
                            });
                        }
                    });
                }
            });
        });
        that.total = data.entityCount;
        layui.use(['laypage'], function(){
            var laypage = layui.laypage;
            laypage.render({
                elem: 'page'
                ,curr:data.pageNo
                ,limit:data.pageSize
                ,jump: function(obj,first){
                    if(!first){
                        if(obj.limit != that.param.pageSize){
                            that.param.pageNo = 1;
                        }else {
                            that.param.pageNo = obj.curr;
                        }
                        that.param.pageSize = obj.limit;
                        that.getRecordList(that.param);
                    }
                }
                ,count: data.entityCount
                ,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            });
        });
    },
    delete:function(data){
        var that = this;
        var type = $('input[name=type]:checked').val();
        var url = type === 1 ? '/api/v1/meteorology/station/delete735?idList='+data.id : '/api/v1/meteorology/station/deleteDay?idList='+data.id;
        $.ajax({
            url: url,
            type:'delete',
            //data:{idList:data.id+""},
            success:function(res){
                if(res.errcode == "0000"){
                    layer.msg("删除成功！",{icon: 1});
                    that.getRecordList(that.param);
                }else{

                }
            },
            error:function(){

            }
        });
    },
    edit:function(data){
        var that = this;
        var param = $("#recordForm").serializeObject();
        param.id = data.id;
        var type = $('input[name=type]:checked').val();
        var url = type === 1 ? '/api/v1/meteorology/station/update735' : '/api/v1/meteorology/station/updateDay';
        $.ajax({
            url: url,
            type:'post',
            data:JSON.stringify({tempday:param}),
            contentType:"application/json",
            success:function(res){
                if(res.errcode == "0000"){
                    layer.msg("编辑成功！",{icon: 1});
                    that.getRecordList(that.param);
                    layer.close(that.layerIndex);
                }else{
                    layer.msg(res.errmsg,{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    getRecordList:function(param){
        var that = this;
        if(param.stationName.length > 4){
            layer.msg("台站名称不超过4个字符！",{icon: 0});
            return;
        }
        that.loading = layer.load(0, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
        var type = $('input[name=type]:checked').val();
        param.type = type;
        $.ajax({
            url:'/api/v1/meteorology/station/getPageTemp',
            type:'post',
            data:param,
            success:function(res){
                if(res.errcode == "0000"){
                    layer.close(that.loading);
                    if(res.data){
                        $(".bottom-wrap .export").attr("disabled",false);
                    }else{
                        $(".bottom-wrap .export").attr("disabled",true);
                    }
                    that.renderTable(res.data)
                }else{

                }
            },
            error:function(){

            }
        });
    }
}

app.init();